<template>
  <BookWrapper
    @downloadBook="downloadBook"
    @handleReturn="handleReturnClick"
    :booksid="booksid"
  >
    <scroll-view
      class="book-content"
      :scroll-y="true"
      @scrolltoupper="handleScrolltoupper()"
      @scrolltolower="handleScrolltolower()"
      lower-threshold="100"
    >
      <div v-for="item in booksDetail" :key="item.id">
        <uni-title :title="item.title"></uni-title>
        <p v-html="item.content"></p>
      </div>
    </scroll-view>
  </BookWrapper>
</template>
<route>
  {
     "layout": "noTabr",
  }
</route>
<script setup lang="ts">
import { ref, toRefs, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import request from "@/utils/request";
import useBooksStore from "@/store/modules/books";
import BookWrapper from "./bookWrapper.vue";
import { writeTxt } from "@/utils/writeTxt";
const booksStore = useBooksStore();
const { booksList } = toRefs(booksStore);

const num = ref(1);
const active = ref(0);
const loading = ref(false);
const chapterDetail = ref(null);
const booksid = ref(0);
interface BookDetail {
  id: number;
  title: string;
  content: string;
}

const booksDetail = ref<BookDetail[]>([]);
// 书架中是否含有该书籍
const iscontains = (): boolean => {
  const list = JSON.parse(uni.getStorageSync("Bookcase") || "[]") || [];
  console.log(list, "list");
  if (list.length === 0) return false;
  let index = list.findIndex(
    (item: any) => item.id === booksStore.booksDetail.id,
  );
  return index > -1 ? true : false;
};
const handleReturnClick = () => {
  let bool: boolean = iscontains();
  if (!bool) {
    const list = JSON.parse(uni.getStorageSync("Bookcase") || "[]") || [];
    uni.showModal({
      title: "提示",
      content: "是否添加书架",
      showCancel: true,
      success: ({ confirm, cancel }) => {
        console.log(confirm, cancel);
        if (confirm) {
          const data = JSON.stringify([
            ...list,
            {
              ...booksStore.booksDetail,
              picture: booksStore.booksDetail.picture,
              Chapterid: chapterDetail.value?.id,
              time: Date.now(),
            },
          ]);
          uni.setStorage({
            key: "Bookcase",
            data: data,
            success: () => {
              uni.navigateBack();
              // uni.redirectTo({
              //   url: `/pages/bookList/bookList?type=${booksStore.booksDetail.type}`,
              // });
            },
            fail: () => {},
          });
        }
        if (cancel) {
          uni.navigateBack();
          // uni.redirectTo({
          //   url: `/pages/bookList/bookList?type=${booksStore.booksDetail.type}`,
          // });
        }
      },
    });
  } else {
    uni.navigateBack();
  }
};
const handleScrolltolower = async () => {
  if (loading.value) return;
  active.value = num.value;
  ++num.value;
  const id = booksList.value[num.value - 1].id;
  await getChapters(id);
};

const handleScrolltoupper = () => {
  if (num.value === 1) return;
  active.value = num.value;
  --num.value;
  const id = booksList.value[num.value - 1].id;
  getChapters(id);
};

const getChapters = async (id: number) => {
  loading.value = true;
  const res = await request({
    url: `chapter/${id}`,
  });
  console.log(res, "res");
  loading.value = false;
  num.value = res?.num;
  chapterDetail.value = res;
  if (active.value > num.value) {
    booksDetail.value.unshift({
      id: res.id,
      title: res.title,
      content: res.content,
    });
  } else {
    booksDetail.value.push({
      id: res.id,
      title: res.title,
      content: res.content,
    });
  }
};

const downloadBook = async () => {
  let allContent = "";
  for (let book of booksList.value) {
    const chapter = await request({
      url: `chapter/${book.id}`,
    });
    allContent += `### ${chapter.title}\n${chapter.content}\n\n`;
  }
  //  #ifndef h5
  const blob = new Blob([allContent], { type: "text/plain" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = booksStore.booksDetail.name + ".txt";
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
  // #endif

  // #ifdef APP-PLUS
  writeTxt("biquge", allContent, booksStore.booksDetail.name + ".txt");
};

onLoad((res: { id: number; bookid?: number }) => {
  const { id, bookid } = res;
  // 判断是否有章节信息

  if (bookid) {
    booksid.value = bookid;
  }
  getChapters(id);
});

onMounted(() => {
  console.log(booksList.value, "booksList");
});
</script>

<style lang="scss" scoped>
.book-content {
  box-sizing: border-box;
  height: 100vh;
  background: #88d8c0;
}
</style>
